﻿using Knight.Common;
using Knight.Common.Excel;
using Knight.Common.Helper;
using Knight.Models.Base;
using Knight.Models.Entity;
using Knight.Web.Infrastructure.Menus;
using Knight.Web.Infrastructure.Mvc;
using Knlght.Data;
using Knlght.Domain;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using WebApp.Areas.Manage.Controllers.Filters;

namespace WebApp.Areas.Manage.Controllers
{
    public class CouponController : BaseAdminController
    {
        [MallAdminMenu("Coupon_List")]
        [Permission("Coupon_List")]
        public ActionResult Index()
        {

            return View(GetUser());
        }

        [MallAdminMenu("Coupon_Empty")]
        [Permission("Coupon_Empty")]
        public ActionResult EmptyOverdueCouponInfo()
        {
            var service = getDefaultService();
            var query = new QueryRequest<CouponInfo>();
            query.Add(o => o.CouponEndTime < DateTime.Now);
            if (service.IsExist(query.SubQueries).IsSuccess)
            {
                ViewBag.Result = service.Remove<CouponInfo>(o => o.CouponEndTime < DateTime.Now);
            }
            else
            {
                ViewBag.Result = new ActionResponse(false, "暂时没有过期优惠券可以清理！");
            }
            return View();
        }

        [MallAdminMenu("Coupon_Type")]
        [Permission("Coupon_Type")]
        public ActionResult Type()
        {
            var rsp = getDefaultService().GetList<ClassACommodity>();
            if (rsp.IsSuccess)
            {
                ViewBag.Result = rsp.Models;
            }
            return View();
        }
        [HttpPost]
        public JsonResult UpdateType(ClassACommodity model)
        {
            var rsp = getDefaultService().Update<ClassACommodity>(model);
            return EJActionJson(rsp);
        }

        [HttpPost]
        public JsonResult UpdatesType(int[] ids, string property, object value)
        {
            var service = getDefaultService();
            if (property.ToLower() == nameof(ClassACommodity.IsShow).ToLower())
            {
                var rsp = service.UpdateToList<ClassACommodity>(o => ids.Contains(o.Id), i => new ClassACommodity { IsShow = (bool)value });
                return EJActionJson(rsp);
            }
            else
            {
                return EJActionJson(false, "该属性修改方法没有实现！");
            }
        }

        [HttpPost]
        public JsonResult RemoveType(int id)
        {
            var rsp = getDefaultService().Remove<ClassACommodity>(o => o.Id == id);
            return EJActionJson(rsp);
        }
        [HttpPost]
        public JsonResult RemovesType(int[] ids)
        {
            var rsp = getDefaultService().Remove<ClassACommodity>(o => ids.Contains(o.Id));
            return EJActionJson(rsp);
        }



        [MallAdminMenu("Coupon_Upload")]
        [Permission("Coupon_Upload")]
        public ActionResult UploadDatas(HttpPostedFileBase file)
        {

            if (file == null)
            {
                return View();
            }
            if (System.IO.File.Exists(Server.MapPath(DConfig.ExcelFile + file.FileName)))
            {
                //存在文件
                ViewBag.Result = new ActionResponse() { IsSuccess = false, Message = "文件已存在" };
            }
            else
            {
                //不存在文件        
               
                string serverpath = Server.MapPath("~/ExcelFile/" + System.IO.Path.GetFileName(file.FileName));           
                try
                {
                    file.SaveAs(serverpath);
                    var execl = new Knight.Common.ExcelHelper(Server.MapPath(DConfig.ExcelFile + file.FileName));
                    var dt = execl.ExcelToDataTable("Page1", true);
                    var models = new List<CouponInfo>();
                    foreach (DataRow item in dt.Rows)
                    {
                        var model = new CouponInfo();
                        model.GoodsId = item["商品Id"].ToString();
                        model.GoodsName = item["商品名称"].ToString();
                        model.CommodityMasterDiagram = item["商品主图"].ToString();
                        model.CommodityDetailsPageLinkAddress = item["商品详情页链接地址"].ToString();
                        model.ClassACommodity = item["商品一级类目"].ToString();
                        model.TaobaoLinks = item["淘宝客链接"].ToString();
                        model.CommodityPrice = Convert.ToDecimal(item["商品价格(单位：元)"]);
                        model.CommodityMonthlySales = Convert.ToInt32(item["商品月销量"]);
                        model.IncomeRatio = Convert.ToDecimal(item["收入比率(%)"]);
                        model.Commission = Convert.ToDecimal(item["佣金"]);
                        model.SellerWangWang = item["卖家旺旺"].ToString();
                        model.SellerID = item["卖家id"].ToString();
                        model.ShopName = item["店铺名称"].ToString();
                        model.PlatformType = item["平台类型"].ToString();
                        model.CouponID = item["优惠券id"].ToString();
                        model.CouponTotal = Convert.ToInt32(item["优惠券总量"]);
                        model.CouponRemaining = Convert.ToInt32(item["优惠券剩余量"]);
                        model.CouponDenomination = item["优惠券面额"].ToString();
                        var mianer = item["优惠券面额"].ToString();
                        if (mianer.Contains("元无条件券"))
                        {
                            var index = mianer.IndexOf("元");
                            model.CouponAmount = Convert.ToDecimal(mianer.Substring(0, index));
                        }
                        else
                        {
                            var index = mianer.IndexOf("减") + 1;
                            var length = mianer.Length - index - 1;
                            model.CouponAmount = Convert.ToDecimal(mianer.Substring(index, length));
                        }
                        model.CouponStartTime = Convert.ToDateTime(item["优惠券开始时间"]);
                        model.CouponEndTime = Convert.ToDateTime(item["优惠券结束时间"]);
                        model.CouponLink = item["优惠券链接"].ToString();
                        model.MerchandiseCouponPromotionLink = item["商品优惠券推广链接"].ToString();
                        models.Add(model);
                    }
                    try
                    {
                        string connectionStr = ConfigurationManager.ConnectionStrings["default"].ConnectionString.ToString();

                        //bulkCopy.BatchSize = 3;
                        //Stopwatch stopwatch = new Stopwatch();//跑表，该类可以进行时间的统计
                       // stopwatch.Start();//跑表开始
                         //将数据源数据写入到目标表中
                        var service = getDefaultService();
                      var rsp=   service.AddToList(models,"T"+ nameof(CouponInfo), DataContext.connectionStr, nameof(CouponInfo.Id), PrimaryKeyType.ID);
                        //跑表结束，Elapsed是统计到的时间
                        ViewBag.Result = rsp;
                    }                                   
                    catch (Exception e)
                    {
                        EmptyFile();
                        ViewBag.Result = new ActionResponse() { IsSuccess = false, Message = "异常原因：" + e.Message };
                    }
                }
                catch (Exception e)
                {
                    EmptyFile();
                    ViewBag.Result = new ActionResponse() { IsSuccess = false, Message = "异常原因：" + e.Message };
                }
            }
            return View();
        }

        [HttpPost]
        public JsonResult EmptyFile()
        {
            var file = Server.MapPath(DConfig.ExcelFile);
            if (!FileHelper.IsEmptyDirectory(file))
            {
                try
                {
                    FileHelper.ClearDirectory(file);
                    return EJActionJson(true, "已清空所有文件！");
                }
                catch (Exception e)
                {
                    throw new EJApplicationException("失败原因：" + e.Message);
                }
            }
            else
            {
                return EJActionJson(false, "当前文件夹没有文件！");
            }
        }

        [HttpPost]
        public JsonResult Paging(PagingParameter parameter)
        {
            var query = new QueryRequest<CouponInfo>();
            //商品名称
            if (parameter.Query.CreateCriterionByString(nameof(CouponInfo.GoodsName)) != null)
            {
                var goodsName = parameter.Query.CreateCriterionByString(nameof(CouponInfo.GoodsName)).Value.ToString();
                query.Add(o => o.GoodsName.Contains(goodsName));
            }
            //商品一级类目
            if (parameter.Query.CreateCriterionByString(nameof(CouponInfo.ClassACommodity)) != null)
            {
                var classACommodity = parameter.Query.CreateCriterionByString(nameof(CouponInfo.ClassACommodity)).Value.ToString();
                query.Add(o => o.ClassACommodity.Contains(classACommodity));
            }
            //店铺名称
            if (parameter.Query.CreateCriterionByString(nameof(CouponInfo.ShopName)) != null)
            {
                var shopName = parameter.Query.CreateCriterionByString(nameof(CouponInfo.ShopName)).Value.ToString();
                query.Add(o => o.ShopName.Contains(shopName));
            }
            //平台类型
            if (parameter.Query.CreateCriterionByString(nameof(CouponInfo.PlatformType)) != null)
            {
                var platformType = parameter.Query.CreateCriterionByString(nameof(CouponInfo.PlatformType)).Value.ToString();
                query.Add(o => o.PlatformType.Contains(platformType));
            }
            //佣金排序
            if (parameter.Query.CreateCriterionByBoolean(nameof(CouponInfo.Commission)) != null)
            {
                var commission = Convert.ToBoolean(parameter.Query.CreateCriterionByBoolean(nameof(CouponInfo.Commission)).Value);
                query.AddOrder(nameof(CouponInfo.Commission), commission);
            }
            //价格排序
            if (parameter.Query.CreateCriterionByBoolean(nameof(CouponInfo.CommodityPrice)) != null)
            {
                var commodityPrice = Convert.ToBoolean(parameter.Query.CreateCriterionByBoolean(nameof(CouponInfo.CommodityPrice)).Value);
                query.AddOrder(nameof(CouponInfo.CommodityPrice), commodityPrice);
            }
            //优惠券金额 
            if (parameter.Query.CreateCriterionByBoolean(nameof(CouponInfo.CouponAmount)) != null)
            {
                var couponAmount = Convert.ToBoolean(parameter.Query.CreateCriterionByBoolean(nameof(CouponInfo.CouponAmount)).Value);
                query.AddOrder(nameof(CouponInfo.CouponAmount), couponAmount);
            }
            var service = getDefaultService();
            var pagingRequest = new PagingRequest<CouponInfo>
            {
                PageIndex = parameter.PageIndex,
                PageSize = parameter.PageSize,
                Query = query
            };
            var rsp = service.Paging(pagingRequest);
            return EJPagingJson(rsp);
        }

        [HttpPost]
        public JsonResult Removes()
        {
            var rsp = getDefaultService().Remove<CouponInfo>(o => o.Id > 0);
            return EJActionJson(rsp);
        }
    }
}